import { useEffect, useState } from 'react';
import { Layout, Typography, Row, Col, Card, Statistic, Table, Tag, Alert, Space, Button, Input, message, Popconfirm } from 'antd';
import { ReloadOutlined, SendOutlined } from '@ant-design/icons';
import 'antd/dist/reset.css';

const { Header, Content } = Layout;
const { Title } = Typography;
const { TextArea } = Input;
const REFRESH_INTERVAL = 10;

export default function App() {
  const [stats, setStats] = useState<any>(null);
  const [pairings, setPairings] = useState<any[]>([]);
  const [devices, setDevices] = useState<any[]>([]);
  const [allDevices, setAllDevices] = useState<any[]>([]);
  const [countdown, setCountdown] = useState(REFRESH_INTERVAL);
  const [loading, setLoading] = useState(false);
  const [testInput, setTestInput] = useState('');

  const fetchAll = async () => {
    setLoading(true);
    try {
      const [statsRes, pairingsRes, devicesRes, allDevicesRes] = await Promise.all([
        fetch('/api/stats').then(r => r.json()),
        fetch('/api/pairings').then(r => r.json()),
        fetch('/api/devices').then(r => r.json()),
        fetch('/api/devices/all').then(r => r.json()),
      ]);
      setStats(statsRes.data);
      setPairings(pairingsRes.data);
      setDevices(devicesRes.data);
      setAllDevices(allDevicesRes.data);
    } catch (e) {
      console.error('数据获取失败:', e);
    } finally {
      setLoading(false);
    }
  };

  const handleManualRefresh = () => {
    fetchAll();
    setCountdown(REFRESH_INTERVAL);
  };

  const handleTestInput = async () => {
    if (!testInput.trim()) {
      message.warning('请输入测试内容');
      return;
    }
    try {
      const response = await fetch('/api/test-input', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text: testInput }),
      });
      if (response.ok) {
        message.success('测试输入已发送');
        setTestInput('');
      } else {
        message.error('发送失败');
      }
    } catch (error) {
      message.error('发送失败: ' + error);
    }
  };

  useEffect(() => {
    fetchAll();
    const timer = setInterval(() => {
      setCountdown(c => {
        if (c <= 1) {
          fetchAll();
          return REFRESH_INTERVAL;
        }
        return c - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  // 统计卡片
  const statCards = (
    <Row gutter={16} style={{ marginBottom: 0 }}>
      <Col xs={12} sm={6}>
        <Card><Statistic title="在线设备数" value={stats?.devices?.online ?? 0} valueStyle={{ color: '#3f8600' }} loading={loading} /></Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card><Statistic title="注册设备数" value={stats?.devices?.total ?? 0} loading={loading} /></Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card><Statistic title="配对关系数" value={stats?.pairing?.activePairings ?? 0} loading={loading} /></Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card><Statistic title="历史设备数" value={allDevices?.length ?? 0} loading={loading} /></Card>
      </Col>
    </Row>
  );

  // 配对关系列表
  const pairingColumns = [
    { title: '配对ID', dataIndex: 'id', key: 'id', width: 200, ellipsis: true },
    { 
      title: '设备A', 
      key: 'device1',
      width: 250,
      render: (_: any, record: any) => (
        <div>
          <div><strong>{record.device1?.name}</strong></div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.device1?.type} - {record.device1?.id}
          </div>
        </div>
      )
    },
    { 
      title: '设备B', 
      key: 'device2',
      width: 250,
      render: (_: any, record: any) => (
        <div>
          <div><strong>{record.device2?.name}</strong></div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.device2?.type} - {record.device2?.id}
          </div>
        </div>
      )
    },
    { 
      title: '状态', 
      dataIndex: 'isActive', 
      key: 'status',
      width: 100,
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'green' : 'gray'}>
          {isActive ? '活跃' : '非活跃'}
        </Tag>
      )
    },
    { 
      title: '创建时间', 
      dataIndex: 'createdAt', 
      key: 'createdAt',
      width: 180,
      render: (timestamp: number) => new Date(timestamp).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: any) => (
        <Popconfirm
          title="确定要删除该配对关系吗？"
          onConfirm={async () => {
            try {
              const res = await fetch(`/api/pairings/${record.id}`, { method: 'DELETE' });
              const result = await res.json();
              if (res.ok && result.success) {
                message.success('配对关系已删除');
                fetchAll();
              } else {
                message.error(result.message || '删除失败');
              }
            } catch (e) {
              message.error('删除失败: ' + e);
            }
          }}
          okText="删除"
          cancelText="取消"
        >
          <Button danger size="small">删除</Button>
        </Popconfirm>
      )
    }
  ];

  // 在线设备表
  const deviceColumns = [
    { title: '设备ID', dataIndex: 'id', key: 'id', width: 200, ellipsis: true },
    { title: '设备名', dataIndex: 'name', key: 'name', width: 150 },
    { title: '类型', dataIndex: 'type', key: 'type', width: 100 },
    { 
      title: '状态', 
      dataIndex: 'isOnline', 
      key: 'status',
      width: 100,
      render: (isOnline: boolean) => (
        <Tag color={isOnline ? 'green' : 'gray'}>
          {isOnline ? '在线' : '离线'}
        </Tag>
      )
    },
    { 
      title: '最后活跃', 
      dataIndex: 'lastSeen', 
      key: 'lastSeen',
      width: 180,
      render: (timestamp: number) => new Date(timestamp).toLocaleString()
    }
  ];

  // 所有注册设备表
  const allDeviceColumns = [
    { title: '设备ID', dataIndex: 'id', key: 'id', width: 200, ellipsis: true },
    { title: '设备名', dataIndex: 'name', key: 'name', width: 150 },
    { title: '类型', dataIndex: 'type', key: 'type', width: 100 },
    { 
      title: '状态', 
      dataIndex: 'isOnline', 
      key: 'status',
      width: 100,
      render: (isOnline: boolean) => (
        <Tag color={isOnline ? 'green' : 'gray'}>
          {isOnline ? '在线' : '离线'}
        </Tag>
      )
    },
    { 
      title: '注册时间', 
      dataIndex: 'timestamp', 
      key: 'registeredAt',
      width: 180,
      render: (timestamp: any) => {
        const date = new Date(Number(timestamp));
        return isNaN(date.getTime()) ? '-' : date.toLocaleString();
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: any) => (
        <Popconfirm
          title="确定要删除该设备吗？"
          onConfirm={async () => {
            try {
              const res = await fetch(`/api/devices/${record.id}`, { method: 'DELETE' });
              const result = await res.json();
              if (res.ok && result.success) {
                message.success('设备已删除');
                fetchAll();
              } else {
                message.error(result.message || '删除失败');
              }
            } catch (e) {
              message.error('删除失败: ' + e);
            }
          }}
          okText="删除"
          cancelText="取消"
        >
          <Button danger size="small">删除</Button>
        </Popconfirm>
      )
    }
  ];

  return (
    <Layout style={{ minHeight: '100vh', background: '#f5f6fa' }}>
      <Header style={{ background: '#001529', padding: '0 24px', height: 64, display: 'flex', alignItems: 'center' }}>
        <Title level={2} style={{ color: '#fff', lineHeight: '64px', margin: 0, background: 'none' }}>
          SmartInput 管理面板
        </Title>
      </Header>
      <Content style={{
        padding: '24px',
        paddingTop: '24px',
        marginTop: 0,
        width: '100vw',
        minHeight: 'calc(100vh - 64px)',
        overflow: 'auto',
        background: '#f5f6fa',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
      }}>
        <div style={{ width: '100%', maxWidth: 1200 }}>
          {/* 页面主标题，最顶部 */}
          <Title level={3} style={{ marginBottom: 16, textAlign: 'center' }}>设备管理看板</Title>
          {/* 自动刷新提示和统计卡片 */}
          <Alert 
            message={
              <Space>
                <span>⏱️ 页面将在 {countdown} 秒后自动刷新</span>
                <Button 
                  type="primary" 
                  icon={<ReloadOutlined />} 
                  onClick={handleManualRefresh}
                  loading={loading}
                  size="small"
                >
                  立即刷新
                </Button>
              </Space>
            } 
            type="info" 
            showIcon 
            style={{ marginBottom: 24 }}
          />
          {statCards}
          {/* 测试输入框 */}
          <Card title="🧪 测试输入框" style={{ margin: '32px 0' }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <TextArea
                value={testInput}
                onChange={(e) => setTestInput(e.target.value)}
                placeholder="输入测试内容..."
                rows={3}
                style={{ width: '100%' }}
              />
              <Button 
                type="primary" 
                icon={<SendOutlined />} 
                onClick={handleTestInput}
                disabled={!testInput.trim()}
              >
                发送测试
              </Button>
            </Space>
          </Card>
          {/* 配对关系列表 */}
          <Card title="🔗 配对关系列表" style={{ marginBottom: 24 }}>
            <Table 
              columns={pairingColumns} 
              dataSource={pairings} 
              rowKey="id" 
              pagination={{ 
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }} 
              size="small" 
              loading={loading}
              scroll={{ x: 1000 }}
            />
          </Card>
          {/* 在线设备 */}
          <Card title="📱 在线设备" style={{ marginBottom: 24 }}>
            <Table 
              columns={deviceColumns} 
              dataSource={devices} 
              rowKey="id" 
              pagination={{ 
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }} 
              size="small" 
              loading={loading}
              scroll={{ x: 800 }}
            />
          </Card>
          {/* 所有注册设备 */}
          <Card title="📋 所有注册设备">
            <Table 
              columns={allDeviceColumns} 
              dataSource={allDevices} 
              rowKey="id" 
              pagination={{ 
                pageSize: 15,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }} 
              size="small" 
              loading={loading}
              scroll={{ x: 800 }}
            />
          </Card>
        </div>
      </Content>
    </Layout>
  );
}
